﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;

namespace GarageService
{
    public class GarageService : IGarageService
    {

        #region GarageService Members

        public ServicebayResponse bookServiceBay(ServicebayRequest req)
        {

            SqlConnection connection = new SqlConnection("Data Source=fastapps04.qut.edu.au;Initial Catalog=n7251998;User ID=n7251998;Password=inb374");
            connection.Open();

            String size = req.size;

            SqlCommand command = new SqlCommand("SELECT MAX(End_date) FROM Servicebay WHERE Size='" + size +"'", connection);


            SqlDataReader reader = command.ExecuteReader();

            String startTime = "-1";

            while (reader.Read())
            {

                startTime = reader.GetString(0);
             
            }

            reader.Close();

            String[] timeSplit = startTime.Split( '-' );


            int year = Int32.Parse(timeSplit[0]);
            int month = Int32.Parse(timeSplit[1]);
            int day  = Int32.Parse(timeSplit[2]);
            DateTime endTime = new DateTime( year, month, day );

            endTime = endTime.AddDays( Int32.Parse(req.numberOfDays) );


            String endDate = endTime.Year +"-"+endTime.Month +"-"+endTime.Day;
            SqlCommand insertCmd = new SqlCommand("INSERT INTO Servicebay (Size, Start_date, End_date, Order_ID) VALUES('" + size + "','" + startTime + "','" + endDate + "','" + req.Order_ID + "')", connection);

            insertCmd.ExecuteNonQuery();
            connection.Close();

            ServicebayResponse res = new ServicebayResponse();

            res.startDate = startTime;
            res.endDate = endDate;
            res.size = size;
            res.numberOfDays = Int32.Parse( req.numberOfDays );
            res.errorMsg = "";
            res.Order_ID = req.Order_ID;


            return res;

        }

        #endregion


        public void cancelServiceBay(int id)
        {
            SqlConnection connection = new SqlConnection("Data Source=fastapps04.qut.edu.au;Initial Catalog=n7251998;User ID=n7251998;Password=inb374");
            connection.Open();

            SqlCommand command = new SqlCommand("DELETE FROM Servicebay WHERE Order_ID='" + id + "'", connection);

            command.ExecuteNonQuery();
            connection.Close();
        }
    }
}
